
/**
  题目:
     给定一个二叉树，原地将它展开为一个单链表。

 

     例如，给定二叉树
     
         1
        / \
       2   5
      / \   \
     3   4   6
     将其展开为：
     
     1
      \
       2
        \
         3
          \
           4
            \
             5
              \
               6
 
     
 
     
 
 
   思路:
      1. 递归：可以按照右左根的顺序遍历
	  2. 非递归：这个慢慢想，将左子树移动到右子树上
	  两者都需要先保留右子树
	 
*/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        while(root){
            TreeNode* o=root->right;
            root->right=root->left;
            root->left=nullptr;
            TreeNode* rightNow=root;
            while(rightNow->right){
                rightNow=rightNow->right;
            }
            rightNow->right=o;
            root=root->right;
        }
    }
   
};


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
TreeNode*pre=nullptr;
    void flatten(TreeNode* root) {
        if(!root){
            return;
        }
        flatten(root->right);
        flatten(root->left);
        root->right=pre;
        root->left=nullptr;
        pre=root;
    }
   
};